﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;
using MensUnoShop.Models;
using MensUnoShop.Models.ViewModels;

namespace MensUnoShop.Filters
{
    /// <summary>
    /// 必須登入才能使用的頁面
    /// 以Session是否存在為依據
    /// 如果Session遺失會去Cookie檢查
    /// </summary>
    public class MemberCheckFilter:ActionFilterAttribute
    {
        private HttpContext _httpcontext = HttpContext.Current;
        //驗證是否有登入
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {          
            if (CheckMember())
                base.OnActionExecuting(filterContext);
            else
            {
                filterContext.Result = new RedirectResult("/");
            }
            
        }

        private bool CheckMember()
        {
            Member im = null;
            bool ismember = true;
            try
            {
                //檢查Session中有沒有Member
                if (_httpcontext.Session["mm"] != null)
                    im = (Member)_httpcontext.Session["mm"];
                else
                {
                    //檢查各種型態的會員
                    //如果有的話存進Session
                    HttpCookie hk = _httpcontext.Request.Cookies["mm"];
                    if (hk != null)
                    {
                        im = (Member)SenerPro.Tools.DeSerialize(SenerPro.Tools.FormBase64URLString(SenerPro.BlowFish.Decrypt(hk.Value, "mavi")));
                    }
                    else
                        ismember = false;
                }
            }
            catch
            {
                im = null;
                ismember = false;
            }
            if (im != null)
            {
                HttpContext.Current.Session["mm"] = im;
            }
            else
                ismember = false;
            im = null;
            return ismember;
        }
        
    }
}